<template>
  <up-list v-if="list.length" @scrolltolower="scrollToLower">
    <slot name="header"></slot>
    <up-list-item v-for="(item, index) in list" :key="index">
      <slot :item="item" :index="index"></slot>
    </up-list-item>
    <up-loadmore :status="status" line />
  </up-list>
  <up-empty v-if="!list.length" mode="list"></up-empty>
</template>
<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';

const props = defineProps({
  immediately: {
    type: Boolean,
    default: true
  },
  limit: {
    type: Number,
    default: 20
  },
  request: {
    type: Function,
    required: true
  },
});

const list = ref([]);
const page = ref(1);
const hasMore = ref(true);
const loading = ref(true);

const status = computed(() => {
  if (loading.value) return 'loading';
  return hasMore.value ? 'loadmore' : 'nomore';
});

onLoad(() => {
  // 立即加载第一页数据
  if(props.immediately) {
    getData();
  }
});

async function getData(pageNum = 1) {
  try {
    loading.value = true
    const res = await props.request({
      page: pageNum,
      limit: props.limit
    });
    loading.value = false
    if (res.data) {
      list.value = pageNum == 1 ? res.data : list.value.concat(res.data);
      hasMore.value = res.current_page < res.last_page;
      page.value = pageNum;
    } else {
      hasMore.value = false;
    }
    
  } catch (error) {
    console.log(error);
    loading.value = false
  }
}

function loadMore () {
  if(hasMore.value) {
    getData(page.value + 1)
  }
};

function scrollToLower() {
  loadMore();
};

function reload() {
  getData()
}

defineExpose({
  reload
});
</script>

<style lang="scss" scoped>
.u-empty {
  padding-top: 200rpx;
}
::v-deep .u-loadmore {
  overflow: hidden;
  padding: 30rpx 0;
  margin: 0 !important;
}
</style>